/**
  * @description: g2--分组条形图（左/右）
  * @author: hj
  * @update: hj(2020-01-14)
  */

import React, { Component } from 'react';
import G2 from '@antv/g2';
import DataSet from '@antv/data-set';
import { getMediaById } from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';

 
@inject('chartStore') 
@observer


class IntervalChart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height - 50 : '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: [],
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            haveData: false,
            legend: 'top',
            padding: '',

            dataNull: false, // 暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件

            pageInitFlag: true,
            affectName: '',
            requireCondition: '',
        };
    };


    componentWillMount() { //初始化
        const _this = this;
        
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData, affectId } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                        _this.setState({
                            pageInitFlag: false
                        })
                        let condition = {};
                        Object.keys(_this.state.requireCondition).forEach(function(keys){
                            condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        this.setState({
            requireCondition: condition,
        });

        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }

    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: false
                    },function() {
                        // 数据处理
                        this.handleData(item.data);
                    })
                }
            })
        }
    }


    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                // 数据处理
                this.handleData(str.data.data);
            } else {
                this.setState({
                    dataNull: true
                })
            }
        } else {
            this.setState({
                dataNull: true
            })
        }
    }
    // 数据处理
    handleData = (storeAllData) => {
        let storeData = storeAllData[0];
        this.setState({
            dataNull: true
        })

        // 非预览界面
        if (this.state.pageFlag != 'preview') {
            // 存储可操作组件数据
            if (storeData.affect && storeData.affect.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveAffectData } = this.props.chartStore;

                let dimensionData = [];
                storeData.affect.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveAffectData(obj);
            }
            // 存储联动组件数据
            if (storeData.requires && storeData.requires.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveRequireData } = this.props.chartStore;

                let dimensionData = [];
                storeData.requires.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveRequireData(obj);
            }
        }

        // 页面初始化
        if (this.state.pageInitFlag) {
            if (storeData.affect &&  storeData.affect.length > 0) {
                this.setState({
                    affectName: storeData.affect[0]
                });
            }
            // 获取选择项
            if (storeData.conditionValues) {
                let selectData = storeData.conditionValues[storeData.affect[0]] ? storeData.conditionValues[storeData.affect[0]] : [];
                this.setState({
                    mainData: selectData
                });
            }
        }


        // 组装当前图例的维度和度量
        let xyArr = [];
        let axisName = [];
        Object.keys(storeData.columnMaps).forEach(function(key){
            axisName.push(key)
        });
        
        axisName.map((item,index) => {
            Object.keys(storeData.columnMaps).forEach(function(key){
                if (key == item) {
                    xyArr.push({
                        key: item,
                        label: storeData.columnMaps[key]
                    })
                }
            });
        })

        if (storeData.data.length > 0) {
            this.setState({
                dataNull: false
            })
        }

        let xAxis = storeData.xaxis ? storeData.xaxis : storeData.xAxis;
        this.setState({
            title: storeData.title,
            xAxis: xAxis,
            fields: storeData.fields,
            chartData: storeData.data,
            axisArr: xyArr,
            color: storeData.colors.split(","),
            haveData: true,
            legend: storeData.legend ? storeData.legend : 'top',
            padding: storeData.padding && storeData.padding != '' ? storeData.padding.split(',') : [30, 10, 10, 80], // 默认legend在top位置,
        })
    }

    // 改变全局变量
    onGlobalVariable = (val) => {
        const { saveAffectId } = this.props.chartStore;
        saveAffectId(this.state.chartId);
        this.props.onGlobalVariable(val);
    }

    

    render() {
        const _this = this;
        let Layer = this.props.layer;

        let chartData = this.state.chartData;
        let axisArr = this.state.axisArr;
        let haveData = this.state.haveData;
        let x = this.state.xAxis, y1,y2;
        let fields= this.state.fields;



        if (haveData && chartData.length > 0) {
            document.getElementById('chart_'+this.state.id+'_'+this.state.chartId).innerHTML = '';
            _this.setState({
                haveData: false
            })

            if (fields){
                y1 = fields[0];
                y2 = fields[1];
            }else{
                y1 = axisArr[1].key;
                y2 = axisArr[2].key;
            }

            let data = [];
            let newData = chartData.map((item) => {
                let obj = {};
                axisArr.map((v) => {
                    if (v.key != x) {
                        obj[v.label] = item[v.key];
                    } else {
                        obj[x] = item[x];
                    }
                })
                return obj;
            });

            newData.map((item,index) => {
                let time = item[x];
                Object.keys(item).forEach(function(key){
                    // console.log(key, x);
                    if (key != x) {
                        data.push({
                            type: key,
                            name: time,
                            value: item[key]
                        })

                    }
                });
            })
            console.log('newData======',newData);
            console.log('data======',data);

            let chart = new G2.Chart({
                container: 'chart_'+this.state.id+'_'+this.state.chartId,
                forceFit: true,
                height: _this.state.height,
                padding: _this.state.padding,
            });
            chart.source(data, {
                value: {
                    nice: false,
                    // alias: '销售额（万）'
                }
            });

            chart.axis('value', false);
            chart.legend({
                position: this.state.legend
            });
            chart.coord().transpose();
            chart.facet('mirror', {
                fields: ['type'],
                autoSetAxis: false,
                transpose: true,
                showTitle: true,
                colTitle: {
                    offsetY: -20, // 列标题垂直方向的偏移
                    style: {
                        fontSize: 12,
                        textAlign: 'center',
                        fill: '#94F5FA'
                    } // 标题文本样式
                },
                padding: [0, 10, 0, 0],
                eachView: function eachView(view, facet) {
                    let facetIndex = facet.colIndex;
                    if (facetIndex === 0) {
                        view.axis('name', {
                            position: 'top',
                            label: {
                                textStyle: {
                                    fill: '#fff',
                                    fontSize: 12
                                },
                            },
                            tickLine: {
                                alignWithLabel: false,
                                length: 0
                            },
                            line: {
                                lineWidth: 0
                            }
                        });
                    } else {
                        view.axis('name', false);
                    }
                    let color = facetIndex === 0 ? _this.state.color[1].split(']')[0] : _this.state.color[3].split(']')[0];
                    view.interval().position('name*value').color(color).size(16).opacity(1).label('value', function(val) {
                        let offset = -4;
                        let shadowBlur = 2;
                        let textAlign = facetIndex === 1 ? 'end' : 'start';
                        let fill = '#fff';
                        if (val < 15) {
                            offset = 4;
                            textAlign = facetIndex === 1 ? 'start' : 'end';
                            fill = '#fff';
                            shadowBlur = 0;
                        }
                        return {
                        //position: 'middle',
                            offset: offset,
                            textStyle: {
                                fill: fill,
                                shadowBlur: shadowBlur,
                                shadowColor: 'rgba(0, 0, 0, .45)',
                                textAlign: textAlign
                            }
                        };
                    });
                }
            });
            chart.tooltip({
                triggerOn: 'click',
                useHtml:true,
                htmlContent:function(title,items){
                    let itemContnt = '';
                    items.map((v,i) => {
                        itemContnt += '<li style="display: block;" style="padding-left: 5px;">'
                                    + '<span style="background-color:'+  v.color +';width: 6px;height: 6px;display: inline-block;border-radius: 3px;margin-right: 3px;" class="g2-tooltip-marker"></span>' 
                                    + '<span style="color: #BDE9FF;">'+  v.point.point.type +'： </span>'
                                    + '<span style="color: '+  v.color +';">'+  v.value +'</span>'
                            + '</li>';
                    })
                    return '<div class="g2-tooltip" style="padding: 5px 15px 15px 15px;position: absolute;left: '+ items[0].x +';top:'+  items[0].y +';">'
                            + '<div class="g2-tooltip-title" style="margin-bottom: 4px;color: #6AEBFC;margin-top: 7px;">'+ title +'</div>'
                            + '<ul class="g2-tooltip-list">'
                                + itemContnt
                            + '</ul>'
                        + '</div>';
                }
            });

            chart.render();
        }

        return (
            <div id={this.state.id+'_'+this.state.chartId} style={{zIndex: 99,width: this.state.width,height: this.state.height,padding: '40px 3% 10px 3%'}}>
                <Layer width={this.state.width} title={this.state.title} chartId={this.state.chartId} choiceData={this.state.mainData} onGlobalVariable={this.onGlobalVariable}></Layer>
                <div id={'chart_'+this.state.id+'_'+this.state.chartId} ></div>
                { this.state.dataNull && <p style={{height: this.state.height,lineHeight: this.state.height+'px',color: '#fff',textAlign: 'center'}}> 暂无数据 </p>}
            </div>
        )
    }


}
export default IntervalChart;

